package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    private List<Map<String,String>> list = new ArrayList<>();
    private AjaxController(){
        Map<String,String> map = new HashMap<>();
        map.put("id", "100");
        map.put("city", "beijing");
        list.add(map);
        map = new HashMap<>();
        map.put("id", "101");
        map.put("city", "shanghai");
        list.add(map);
    }
    @PutMapping("/doAjaxPut")
    public String doUpdateObject(@RequestParam Map<String,String> paramMap){
        String id=paramMap.get("id");
        Iterator<Map<String,String>> it=list.iterator();
        while(it.hasNext()){
            Map<String,String> map=it.next();
            if(map.get("id").equals(id)){
                map.put("city", paramMap.get("city"));
                //....
            }
        }
        return "update ok";
    };
    @DeleteMapping("/doAjaxDelete/{id}")
    public String doDeleteObject(@PathVariable String id){
        Iterator<Map<String, String>> it = list.iterator();
        while (it.hasNext()){
            Map<String,String> map = it.next();
            if (map.get("id").equals(id)){
                it.remove();
            }
        }
//        for (Map<String, String> map :list){
//            if (map.get("id").equals(id)){
//                map.remove(id);
//            }
//        }
        return "delete ok";
    }
    @GetMapping(path = {"/doAjaxGet/{city}","/doAjaxGet"})
    public List<Map<String,String>> doAjaxGet(@PathVariable(required = false) String city){
        if (city==null||"".contains(city)){return list;}
        List<Map<String,String>> queryResult=new ArrayList<>();
        for (Map<String,String> map :list){
            if (map.get("city").contains(city)){
                queryResult.add(map);
            }
        }
        return queryResult;
    }
    @PostMapping("/doAjaxPost")
    public String doSaveObject(@RequestParam Map<String,String> map){
        list.add(map);
        return "Save OK";
    }
    @PostMapping("/doAjaxJsonPost")
    public String doSaveJsonObject(@RequestBody Map<String,String> map){
        list.add(map);
        return "Save Json OK";
    }

//    @RequestMapping("/doAjaxGet")
//    @ResponseBody
//    public List<Map<String,String>> doAjaxGet(){
//        return list;
//    }
    @GetMapping("/doAjaxStart")
    public String doAjaxStart() throws InterruptedException {
        Thread.sleep(3000);
        return "Response Result of Ajax Request 01";
    }
}
